//
//  MSShowerDetailVC.m
//  MS
//
//  Created by Yuan on 13-3-20.
//  Copyright (c) 2013年 He Yuan. All rights reserved.
//

#import "MSShowerDetailVC.h"
#import "CustomNavgationBar.h"
#import "MSShowerDetailBottomView.h"
#import "MSShowerInfoView.h"

#import "UIColor+ColorUtils.h"
#import "ImageScrollView.h"

#import "CommentVC.h"

#import "MSUserHomeVC.h"

#import "MSChatVC.h"

@interface MSShowerDetailVC ()<UIGestureRecognizerDelegate,UIScrollViewDelegate>
{
    CustomNavgationBar *topBar;
    
    MSShowerDetailBottomView *bottomBar;
    
    IBOutlet UIScrollView *mainScrollView;
    
    MSShowerInfoView *userInfoView;
    
    NSMutableArray *datas;
        
    NSMutableArray *pagesArray;
    
    NSUInteger currentPage ;
    
    NSUInteger totalPages;
}
@property(nonatomic,retain)    UIScrollView *mainScrollView;
@property(nonatomic,retain)    MSShowerInfoView *userInfoView;
@property(nonatomic,retain)    CustomNavgationBar *topBar;
@property(nonatomic,retain)    MSShowerDetailBottomView *bottomBar;
@property(nonatomic,retain)    NSMutableArray *datas;
@property(nonatomic,retain)    NSMutableArray *pagesArray;
@end

@implementation MSShowerDetailVC
@synthesize topBar;
@synthesize datas;
@synthesize bottomBar;
@synthesize mainScrollView;
@synthesize userInfoView;
@synthesize pagesArray;


-(void)dealloc
{
    self.mainScrollView = nil;
    self.pagesArray = nil;
}


-(void)viewDidUnload
{
    [super viewDidUnload];
    
    HYLog(@"释放内存....");
    
    [pagesArray removeAllObjects];
    
    [self.mainScrollView.subviews makeObjectsPerformSelector:@selector(removeFromSuperview)];
    
    self.mainScrollView = nil;
}


- (id)initWithDatas:(NSArray *)alldatas currentIndex:(NSInteger)index
{
    self = [super init];
    
    if (self)
    {
        currentPage = index;
        
        datas = [[NSMutableArray alloc] initWithArray:alldatas];
        
        pagesArray = [[NSMutableArray alloc]init];
        
        for(SInt16 i = 0 ; i < [datas count];i++)
        {
            [pagesArray addObject:[NSNull null]];
        }

        totalPages = [datas count];

    }
    return self;
}

-(void)loadView
{
    [super loadView];
    
//    self.view.backgroundColor = [UIColor blackColor];
    
    self.mainScrollView = [[UIScrollView alloc]initWithFrame:self.view.bounds];
    self.mainScrollView.delegate = self;
    self.mainScrollView.pagingEnabled = YES;
    self.mainScrollView.backgroundColor = [UIColor clearColor];
    self.mainScrollView.contentSize = CGSizeZero;
    self.mainScrollView.showsVerticalScrollIndicator = NO;
    self.mainScrollView.showsHorizontalScrollIndicator = NO;
    [self.view addSubview:self.mainScrollView];
    
    topBar = [[CustomNavgationBar alloc]initWithFrame:self.navigationController.navigationBar.bounds];
    [self.view addSubview:topBar];
    
    UIImage *btnImage = [UIImage imageNamed:@"nav_btn_back"];
    UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
    [btn setFrame:CGRectMake(5, topBar.frame.size.height/2 - btnImage.size.height/2, btnImage.size.width, btnImage.size.height)];
    [btn setBackgroundImage:[btnImage stretchableImageWithLeftCapWidth:2 topCapHeight:2] forState:UIControlStateNormal];
    btn.tag = 1;
    [btn addTarget:self action:@selector(back:) forControlEvents:UIControlEventTouchUpInside];
    [topBar addSubview:btn];
    
    UILabel *titleLbl = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, 200, 44)];
    [titleLbl setTextAlignment:UITextAlignmentCenter];
    titleLbl.textColor = ThemeTitleColor;
    titleLbl.backgroundColor = [UIColor clearColor];
    titleLbl.font = FONT_TITLE;
    titleLbl.tag = 2;
    titleLbl.center = self.topBar.center;
    titleLbl.text = HYLocalizedString(@"详细");
    [self.topBar addSubview:titleLbl];
    
    bottomBar = [[MSShowerDetailBottomView alloc]initWithFrame:CGRectMake(0,0, self.view.frame.size.width, 0) delegate:self];
    [self.view addSubview:bottomBar];
    UIViewSetFrameY(bottomBar, self.view.frame.size.height - bottomBar.frame.size.height);    
    
    CGFloat userinfo_height = 87.0f;
    userInfoView = [[MSShowerInfoView alloc]initWithFrame:CGRectMake(0, bottomBar.frame.origin.y - userinfo_height - 5.0, self.view.frame.size.width, userinfo_height)];
    [self.view addSubview:userInfoView];
    
    [userInfoView.avatarButton addTarget:self action:@selector(userHomePage:) forControlEvents:UIControlEventTouchUpInside];

    
    UITapGestureRecognizer *singleTapOneFinger = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(handleSingleTap:)];
    singleTapOneFinger.numberOfTapsRequired = 1;
    singleTapOneFinger.numberOfTouchesRequired = 1;
    singleTapOneFinger.delegate = self;
    [self.view addGestureRecognizer:singleTapOneFinger];
}

-(void)userHomePage:(UIButton *)btn
{
    NSDictionary *item = [datas objectAtIndex:currentPage];
    MSUserHomeVC *vc = [[MSUserHomeVC alloc]initWithUID:[item objectForKey:@"uid"] userName:[item objectForKey:@"user_name"]];
    [self.navigationController pushViewController:vc animated:YES];
}


-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];    
    [self.navigationController setNavigationBarHidden:YES animated:YES];
}

-(void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [self.navigationController setNavigationBarHidden:NO animated:YES];
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    [self setTitle:HYLocalizedString(@"详细") showBackButton:YES];
        
    [self loadScrollViewWithPage:currentPage];
    
    self.mainScrollView.contentSize = CGSizeMake(self.mainScrollView.frame.size.width * totalPages, self.mainScrollView.frame.size.height);
    
    CGPoint point =  CGPointMake(self.mainScrollView.frame.size.width*currentPage, 0);
    [self.mainScrollView setContentOffset:point];
    
    [self refreshUI];
	// Do any additional setup after loading the view.
}

-(void)configureViews:(BOOL)animation
{
    [super configureViews:animation];
}


-(void)refreshUI
{
    NSDictionary *item = [datas objectAtIndex:currentPage];
    ((UILabel *)([self.topBar viewWithTag:2])).text = [item objectForKey:@"user_name"];    
    [userInfoView loadAvatarImage:[item objectForKey:@"avatar"] ];
    NSString *content = [item objectForKey:@"content"];
    [userInfoView refreshDescription:content];
    
    UILabel *likecountLbl = (UILabel *)[[bottomBar viewWithTag:1] viewWithTag:100];
    [likecountLbl setText:[item objectForKey:@"collect_count"]];
    
    UILabel *commentCountLbl = (UILabel *)[[bottomBar viewWithTag:2] viewWithTag:100];
    [commentCountLbl setText:[item objectForKey:@"comment_count"]];
}

- (void)loadScrollViewWithPage:(int)page
{
    if (page < 0) return;
    if (page >= totalPages) return;
    ImageScrollView *imageScrollView = [pagesArray objectAtIndex:page];
    if ((NSNull *)imageScrollView == [NSNull null])
    {
        NSDictionary *item = [datas objectAtIndex:page];
        imageScrollView = [[ImageScrollView alloc]initWithFrame:CGRectMake(self.mainScrollView.frame.size.width*page,0,self.mainScrollView.frame.size.width, self.mainScrollView.frame.size.height) url:[item objectForKey:@"src"] target:self];
        [pagesArray replaceObjectAtIndex:page withObject:imageScrollView];
        [self.mainScrollView addSubview:imageScrollView];
    }
    else
    {
		imageScrollView.zoomScale = 1.0;
    }
}



-(void)handleSingleTap:(UITapGestureRecognizer*)recognizer
{
    CGFloat bottomBar_y = self.bottomBar.frame.origin.y;
    bottomBar_y = bottomBar_y<self.view.frame.size.height?self.view.frame.size.height:(self.view.frame.size.height - bottomBar.frame.size.height);
    [UIView animateWithDuration:0.2 animations:^(void)
     {
         if (self.topBar.frame.origin.y < 0)
         {
             self.view.backgroundColor = [UIColor colorWithString:@"#f1eee9"];
         }
         else
         {
             self.view.backgroundColor = [UIColor blackColor];
         }
         UIViewSetFrameY(self.topBar, self.topBar.frame.origin.y<0?0:-self.topBar.frame.size.height);
         UIViewSetFrameY(self.bottomBar,bottomBar_y);
         UIViewSetFrameX(userInfoView,userInfoView.frame.origin.x>0?0:userInfoView.frame.size.width);
     }completion:^(BOOL f){
         
     }];
}

//添加事件过滤ios5中uibutton无法相应的问题
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch
{
    return ! ([touch.view isKindOfClass:[UIControl class]]);
}

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    CGFloat pageWidth = scrollView.frame.size.width;
    
    int page = floor((scrollView.contentOffset.x - pageWidth / 2) / pageWidth) + 1;
    
    BOOL isNeedUpdate = (currentPage == page)?NO:YES;
    
    currentPage = page;
    
    if ([[datas objectAtIndex:page] objectForKey:@"user_name"] == nil)
    {
        //        [self requestData];
    }
    else
    {
        //        [self refreshUI];
    }
    
    [self loadScrollViewWithPage:page - 1];
    
    [self loadScrollViewWithPage:page];
    
    [self loadScrollViewWithPage:page + 1];
    
    for(int i = 0 ;i < [pagesArray count];i++)
    {
        if(i== currentPage -1 ||i == currentPage || i == currentPage + 1)continue;
        
        ImageScrollView *imageScrollView = [pagesArray objectAtIndex:i];
        
        if ((NSNull *)imageScrollView != [NSNull null])
        {
            [imageScrollView.subviews makeObjectsPerformSelector:@selector(removeFromSuperview)];
            [imageScrollView removeFromSuperview];
            [pagesArray replaceObjectAtIndex:i withObject:[NSNull null]];
            imageScrollView = nil;
        }
    }
    
    if (isNeedUpdate)[self refreshUI];
    
}



-(void)toolBarItemActon:(UIButton *)sender
{
    switch ([sender tag]) {
        case 1:
            [self likeAction];
            break;
        case 2:
            [self commentAction];
            break;
        case 3:
            [self privateMessageAction];
            break;
        case 4:
            [self favoriteAction];
            break;
        case 5:
            [self shareAction];
            break;
        default:
            break;
    }
}

-(void)handleLikeOrFavoriteAction:(NSString *)collect shareid:(NSString *)shareid
{
    NSDictionary *p = [NSDictionary dictionaryWithObjectsAndKeys:
                       [[MSSetting sharedSetting]getAccountID],@"uid",
                       shareid,@"share_id",
                       collect,@"collect",nil];
    
    [WebService  getRequestAction:APILikeAndFavorite
                            param:p
                          success:^(NSDictionary *info,NSError *error)
     {
         if (error == nil)
         {
             HYLog(@"%@",info);
             [MSTool refreshHUDText:HYLocalizedString(@"处理成功!")];
             NSDictionary *item = [datas objectAtIndex:currentPage];
             NSMutableDictionary *new_item ;
             if ([collect isEqualToString:@"0"])
             {
                 NSInteger count = [[item objectForKey:@"collect_count"] intValue];
                 count++;
                 new_item = [NSMutableDictionary dictionaryWithDictionary:item];
                 [new_item setObject:[NSString stringWithFormat:@"%d",count] forKey:@"collect_count"];
                 [datas replaceObjectAtIndex:currentPage withObject:new_item];
                 [self refreshUI];
             }
         }
         [MSTool showError:error];
     } failure:^(id info ,NSError *error){
         [MSTool showError:error];
     } progress:self.navigationController.view];
}

-(void)likeAction
{
    [self handleLikeOrFavoriteAction:@"0" shareid:[[datas objectAtIndex:currentPage] objectForKey:@"share_id"]];
}

-(void)favoriteAction
{
    [self handleLikeOrFavoriteAction:@"1" shareid:[[datas objectAtIndex:currentPage] objectForKey:@"share_id"]];
}

-(void)commentAction
{
    CommentVC *vc = [[CommentVC alloc]initWithInfo:[datas objectAtIndex:currentPage]];
    vc.fromViewController = self;
    NSString *shareID = [[datas objectAtIndex:currentPage] objectForKey:@"share_id"];
    vc.shareID = shareID;
    [self.navigationController pushViewController:vc animated:YES];    
}

-(void)privateMessageAction
{
    NSDictionary *item = [datas objectAtIndex:currentPage];
    NSDictionary *chatinfo = [NSDictionary  dictionaryWithObjectsAndKeys:
                              [item objectForKey:@"user_name"],@"t_user_name",
                              [item objectForKey:@"uid"],@"tuid",
                              nil];
    MSChatVC *vc = [[MSChatVC alloc]initWithInfo:chatinfo];
    [self.navigationController pushViewController:vc animated:YES];
}

-(void)shareAction
{
    
    
}


- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
